using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using _RobotInspection.Services;
using _RobotInspection.Interfaces;
using _RobotInspection.Attributes;
using _RobotInspection.DTO;
using _RobotInspection.Models;

namespace _RobotInspection.Controllers
{

    /// <summary>
    /// APP日常点检管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]

    public class DailyInspectionManagementController : ControllerBase
    {
        private readonly IDailyInspectionManagementService _service;
        public DailyInspectionManagementController(IDailyInspectionManagementService dailyInspectionManagementService)
        {
            _service = dailyInspectionManagementService;
        }

        /// <summary>
        /// 获取当前用户负责的设备列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="date">目标日期（默认当天）</param>
        /// <param name="statusFilter">状态过滤：1-已完成，0-未完成</param>
        /// <param name="planType">计划类型过滤：1-日，2-周，3-月，4-一次性</param>
        /// <param name="keyword">设备名称或编码模糊查询</param>
        /// <returns>设备卡片列表</returns>
        [HttpGet("my-equipment-summary")]
        [ApiStatus(ApiStatusEnum.Completed)]
        public async Task<ActionResult<ApiResponse<List<DailyEquipmentSummaryDto>>>> GetMyEquipmentSummary([FromQuery] long userId, [FromQuery] DateTime? date = null, [FromQuery] byte? statusFilter = null, [FromQuery] byte? planType = null, [FromQuery] string? keyword = null)
        {
            var targetDate = date ?? DateTime.Today;
            var result = await _service.GetUserDailyEquipmentSummaryAsync(userId, targetDate, planType, keyword, statusFilter);
            return new OkObjectResult(result);
        }

        /// <summary>
        /// 获取设备详情与点检清单（备用）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="equipmentId">设备ID</param>
        /// <param name="date">目标日期（默认当天）</param>
        /// <param name="status">项次状态过滤（可选：1-正常，2-异常，3-待处理）</param>
        /// <returns>设备详情与当天任务的点检清单</returns>
        [HttpGet("equipment/{equipmentId}")]
        [ApiStatus(ApiStatusEnum.Developing)]
        public async Task<ActionResult<ApiResponse<EquipmentTaskDetailDto>>> GetEquipmentDetail([FromQuery] long userId, [FromRoute] long equipmentId, [FromQuery] DateTime? date = null, [FromQuery] byte? status = null, [FromQuery] int PageIndex = 1, [FromQuery] int PageSize = 20)
        {
            var targetDate = date ?? DateTime.Today;
            var taskIdResult = await _service.GetTaskIdForUserAndEquipmentAsync(userId, equipmentId, targetDate);
            if (taskIdResult.Code != 200 || taskIdResult.Data == null)
            {
                return new OkObjectResult(taskIdResult);
            }

            var taskIdProp = taskIdResult.Data.GetType().GetProperty("TaskId");
            if (taskIdProp == null)
            {
                return new OkObjectResult(ApiResponse<object>.Error("任务数据格式异常", 500));
            }
            var taskId = (long)(taskIdProp.GetValue(taskIdResult.Data) ?? 0L);
            var details = await _service.GetTaskDetailsAsync(taskId, PageIndex, PageSize, status);
            return new OkObjectResult(details);
        }

        /// <summary>
        /// 根据任务ID获取设备详情与点检项次
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <param name="status">项次状态过滤（可选：1-正常，2-异常，3-待处理）</param>
        /// <returns>设备任务详情及项次列表</returns>
        [HttpGet("tasks/{taskId}")]
        [ApiStatus(ApiStatusEnum.Completed)]
        public async Task<ActionResult<ApiResponse<EquipmentTaskDetailDto>>> GetTaskDetailById([FromRoute] long taskId, [FromQuery] byte? status = null, [FromQuery] int PageIndex = 1, [FromQuery] int PageSize = 20)
        {
            var result = await _service.GetTaskDetailsAsync(taskId, PageIndex, PageSize, status);
            return new OkObjectResult(result);
        }

        /// <summary>
        /// 获取点检项次的执行详情
        /// </summary>
        /// <param name="recordId">记录ID</param>
        /// <returns>点检项次详情</returns>
        [HttpGet("records/{recordId}")]
        [ApiStatus(ApiStatusEnum.Completed)]
        public async Task<ActionResult<ApiResponse<InspectionRecordDetailDto>>> GetRecordDetail([FromRoute] long recordId)
        {
            var result = await _service.GetRecordByIdAsync(recordId);
            return new OkObjectResult(result);
        }

        /// <summary>
        /// 更新或保存点检项次执行结果（支持正常与异常提交流程）
        /// </summary>
        /// <param name="dto">提交的表单数据（multipart/form-data）。包含 RecordId 与 TaskId。
        /// 必填：RecordId、TaskId、ActualValue、ResultStatus。
        /// 正常：可选 Remark、InspectionPhoto、InspectionTime、InspectorId。
        /// 异常：需提供 NextAssignParty，建议同时填写 IssueDescription，并可上传 InspectionPhoto 与 RepairPhoto。</param>
        /// <returns>保存结果</returns>
        [HttpPut("records")]
        [Consumes("multipart/form-data")]
        [ApiStatus(ApiStatusEnum.Completed)]
        public async Task<ActionResult<ApiResponse<object>>> UpsertRecord([FromForm] UpsertRecordSubmitDto dto)
        {
            var result = await _service.UpsertRecordAsync(dto.TaskId, dto.ActualValue, dto.ResultStatus, dto.Remark, dto.InspectionPhoto, dto.RepairPhoto, dto.InspectionTime, dto.IssueDescription, dto.NextAssignParty, dto.InspectorId, dto.AddAttentionItem, dto.AttentionAbnormalName, dto.AttentionDescription, dto.ReporterUserId, dto.RecordId ?? 0);
            return new OkObjectResult(result);
        }


    }
}
